from flask import Flask, request, jsonify, render_template, send_from_directory
from flask_cors import CORS
import os
import base64
import requests
import json
from werkzeug.utils import secure_filename

app = Flask(__name__)
CORS(app)

# 配置上传文件夹
UPLOAD_FOLDER = 'uploads'
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'bmp', 'tiff', 'pdf'}

if not os.path.exists(UPLOAD_FOLDER):
    os.makedirs(UPLOAD_FOLDER)

app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 10 * 1024 * 1024  # 10MB max file size

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/static/<path:filename>')
def static_files(filename):
    return send_from_directory('static', filename)

@app.route('/api/ocr', methods=['POST'])
def ocr_api():
    try:
        if 'file' not in request.files:
            return jsonify({'error': '没有选择文件'}), 400
        
        file = request.files['file']
        if file.filename == '':
            return jsonify({'error': '没有选择文件'}), 400
        
        if file and allowed_file(file.filename):
            # 保存文件
            filename = secure_filename(file.filename)
            filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
            file.save(filepath)
            
            # 获取文件大小
            file_size = os.path.getsize(filepath)
            
            # 模拟OCR结果
            mock_result = {
                'text': f'这是 {filename} 的识别结果\n\n文件大小: {file_size} 字节\n\n这是模拟的OCR文字识别内容\n支持多行文字识别\n可以识别各种格式的图片\n\n识别时间: {__import__("datetime").datetime.now().strftime("%Y-%m-%d %H:%M:%S")}',
                'confidence': 0.95,
                'filename': filename,
                'file_size': file_size,
                'words': [
                    {'text': f'文件名: {filename}', 'confidence': 0.98},
                    {'text': '这是模拟的OCR识别内容', 'confidence': 0.96},
                    {'text': '支持多行文字识别', 'confidence': 0.94},
                    {'text': '可以识别各种格式的图片', 'confidence': 0.95}
                ]
            }
            
            return jsonify({
                'success': True,
                'result': mock_result,
                'filename': filename
            })
        else:
            return jsonify({'error': '不支持的文件格式'}), 400
            
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/api/batch_ocr', methods=['POST'])
def batch_ocr_api():
    try:
        files = request.files.getlist('files')
        if not files:
            return jsonify({'error': '没有选择文件'}), 400
        
        results = []
        for i, file in enumerate(files):
            if file and allowed_file(file.filename):
                filename = secure_filename(file.filename)
                filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
                file.save(filepath)
                
                file_size = os.path.getsize(filepath)
                
                # 模拟OCR结果
                mock_result = {
                    'filename': filename,
                    'text': f'文件 {i+1}: {filename}\n文件大小: {file_size} 字节\n这是批量识别的模拟结果\n支持多文件同时处理',
                    'confidence': 0.93,
                    'file_size': file_size
                }
                results.append(mock_result)
        
        # 合并所有结果
        combined_text = '\n\n=== 批量识别结果 ===\n\n' + '\n\n---\n\n'.join([r['text'] for r in results])
        
        return jsonify({
            'success': True,
            'results': results,
            'combined_result': {
                'text': combined_text,
                'total_files': len(results),
                'timestamp': __import__("datetime").datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            }
        })
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

if __name__ == '__main__':
    print("=" * 50)
    print("🚀 OCR服务启动中...")
    print("📍 访问地址: http://localhost:5000")
    print("📁 上传目录: uploads/")
    print("💡 支持格式: JPG, PNG, BMP, PDF, TIFF, GIF")
    print("📏 最大文件: 10MB")
    print("=" * 50)
    app.run(debug=True, host='0.0.0.0', port=5000)